"""DcmConvertTest
    此文件的编写目的用于尝试纠正dcm转nrrd时出现的各种方向倒转问题

    1. 估计在nrrd的space directions中，第三个矩阵为负数的需要旋转
    2. 估计需要进行flip的厂商:
        1. xxxxxxxxxxxx
"""
import SimpleITK as sitk
import numpy as np
import pydicom
import os
import nrrd
from DicomAutoConvert.dicom_convert_0619 import get_root_dcm_files, convert_all

"""####################### 1. 测试添加方向向量减少翻转 #################################"""
# 此方法测试添加了一些方向矩阵后进行保存的结果
# 结论：在测试数据中保证了大多数据的正确方向(space origin)
def dcm_convert_test(root_dcm_dict: dict, save_path: str):
    os.makedirs(save_path, exist_ok=True)
    for root in root_dcm_dict.keys():
        try:
            reader = sitk.ImageSeriesReader()
            series_file_names = reader.GetGDCMSeriesFileNames(root, root_dcm_dict[root])

            ds = pydicom.dcmread(series_file_names[0])
            save_name = ds.AccessionNumber + ".nrrd"
            spacing = ds.PixelSpacing
            spacing.append(ds.SliceThickness)
            orientation = ds.ImageOrientationPatient
            position = ds.ImagePositionPatient

            reader.SetFileNames(series_file_names)
            dicom_series = reader.Execute()

            dicom_series.SetSpacing(spacing)
            direction_cosines = np.array(orientation).reshape(2, 3)
            normal = np.cross(direction_cosines[0], direction_cosines[1])
            direction_cosines = np.vstack([direction_cosines, normal])  # 添加法向量
            dicom_series.SetDirection(direction_cosines.flatten())
            dicom_series.SetOrigin(position)

            sitk.WriteImage(dicom_series, os.path.join(save_path, save_name))
            print("Convert", save_name)
        except Exception as e:
            print("Convert Error", root_dcm_dict[root], str(e))


a = r"B:\projects\dicom_data_test"
# d = get_root_dcm_files(a)
# dcm_convert_test(d, r"Z:\Development\Ftp\dicom_save_test")

# d1 = r"Z:\Development\Ftp\dicom_save"
# d2 = r"Z:\Development\Ftp\dicom_save_test"


"""####################### 2. 打印相关数据，查看是否能直接拷贝头信息 -- 可以 -- #################################"""
# ZX3687918, ZX3708577
# JS-862944 LY-2700155
# d1, h1 = nrrd.read(os.path.join(d1, "LY-2700155.nrrd"))
# d2, h2 = nrrd.read(os.path.join(d2, "LY-2700155.nrrd"))

# print(h1)
# print(h2)
# print(h1['space directions'])
# print(h2['space directions'])
# h1_matrix = h1['space directions']
# print(np.cross(h1_matrix[0], h1_matrix[1]))
# nrrd.write("out.nrrd", d1, h2)


"""####################### 3，打印厂家信息 #################################"""
def get_root_dcm_files_test(root_start: str):
    root_dcm_dict = {}

    for root, dirs, files in os.walk(root_start):
        filter_dcm_file = []
        for each_file in files:
            if each_file.lower().endswith(".dcm"):
                filter_dcm_file.append(each_file)

        if len(filter_dcm_file) == 0:
            continue

        # TODO: 文件夹可能存在多个脏数据
        reader = sitk.ImageSeriesReader()
        root_dcm_dict[root] = reader.GetGDCMSeriesIDs(root)[-1]
        series_file_names = reader.GetGDCMSeriesFileNames(root, root_dcm_dict[root])
        ds = pydicom.dcmread(series_file_names[0])
        print("Read", root, root_dcm_dict[root], ds.Manufacturer)

    return root_dcm_dict

def convert_all_test(root_dcm_dict: dict, save_path: str):
    os.makedirs(save_path, exist_ok=True)
    for root in root_dcm_dict.keys():
        try:
            reader = sitk.ImageSeriesReader()
            series_file_names = reader.GetGDCMSeriesFileNames(root, root_dcm_dict[root])

            ds = pydicom.dcmread(series_file_names[0])
            save_name = ds.AccessionNumber + "_" + ds.Manufacturer + ".nrrd"

            reader.SetFileNames(series_file_names)
            dicom_series = reader.Execute()

            sitk.WriteImage(dicom_series, os.path.join(save_path, save_name))
            print("Convert", save_name)
        except Exception as e:
            print("Convert Error", root_dcm_dict[root], str(e))

d_t = get_root_dcm_files_test(a)
convert_all_test(d_t, r"B:\projects\manu")